package com.zhiche.lisa.bms.service.driver.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zhiche.lisa.bms.dao.mapper.driver.FuelTypeMapper;
import com.zhiche.lisa.bms.dao.model.driver.FuelPriceEffective;
import com.zhiche.lisa.bms.dao.model.driver.FuelType;
import com.zhiche.lisa.bms.service.driver.IFuelPriceEffectiveService;
import com.zhiche.lisa.bms.service.driver.IFuelTypeService;
import com.zhiche.lisa.bms.pojo.vo.driver.FuelTypeQueryConditionVO;
import com.zhiche.lisa.bms.pojo.vo.driver.FuelTypeVO;
import com.zhiche.lisa.core.supports.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 燃油类型表 服务实现类
 * </p>
 *
 * @author zhaoguixin
 * @since 2018-08-30
 */
@Service
@Slf4j
public class FuelTypeServiceImpl extends ServiceImpl<FuelTypeMapper, FuelType> implements IFuelTypeService {

    @Autowired
    private IFuelPriceEffectiveService fuelPriceEffectiveService;

    /**
     * 分页查询燃油类型
     *
     * @param pageVO
     * @return
     */
    @Override
    public Page<FuelTypeVO> listByPage(Page<FuelTypeVO> pageVO) {
        if (pageVO == null) {
            return null;
        }
        pageVO.setOrderByField("update_time");
        pageVO.setAsc(false);
        EntityWrapper<FuelType> ew = whereCondition(pageVO);
        List<FuelType> listFuelType = baseMapper.selectPage(pageVO,ew);
        List<FuelTypeVO> listVO = Lists.newArrayList();
        listFuelType.forEach(fuelType -> {
            FuelTypeVO fuelTypeVO = new FuelTypeVO();
            BeanUtils.copyProperties(fuelType,fuelTypeVO);
            listVO.add(fuelTypeVO);
        });
        pageVO.setRecords(listVO);
        return pageVO;
    }


    /**
     * 添加燃油类型
     *
     * @param fuelTypeVO
     * @param br
     * @return
     */
    @Override
    public Integer add(FuelTypeVO fuelTypeVO, BindingResult br) {
        log.info("FuelTypeServiceImpl.add params : {}", fuelTypeVO);
        if (Objects.isNull(fuelTypeVO)) {
            log.error("DFuelTypeServiceImpl.add param form must not be null");
            throw new BaseException("燃油类型表单不能为空");
        }
        //验证表单
        verificationForm(br);
        /**
         * 判断燃油编码是否唯一
         */
        this.verificationCodeOrNameUnique(fuelTypeVO.getId(), fuelTypeVO.getFuelName(), fuelTypeVO.getFuelCode());
        FuelType fuelType = new FuelType();
        BeanUtils.copyProperties(fuelTypeVO, fuelType);
        this.insert(fuelType);

        return fuelType.getId();
    }

    /**
     * 更新燃油类型
     *
     * @param fuelTypeVO
     * @param br
     * @return
     */
    @Override
    public Boolean update(FuelTypeVO fuelTypeVO, BindingResult br) {
        log.info("FuelTypeServiceImpl.update params : {}", fuelTypeVO);

        if (Objects.isNull(fuelTypeVO)) {
            log.error("FuelTypeServiceImpl.update params form must not be null");
            throw new BaseException("燃油类型表单不能为空");
        }

        //验证表单
        verificationForm(br);

        /**
         * 判断燃油编码是否唯一
         */
        this.verificationCodeOrNameUnique(fuelTypeVO.getId(), fuelTypeVO.getFuelCode(), fuelTypeVO.getFuelName());

        FuelType fuelType = new FuelType();
        BeanUtils.copyProperties(fuelTypeVO, fuelType);
        return this.updateById(fuelType);
    }

    /**
     * 删除燃油类型
     *
     * @param id
     * @return
     * @throws BaseException
     */
    @Override
    public Boolean del(Integer id) throws BaseException {
        log.info("FuelTypeServiceImpl.delete param : {}", id);

        if (Objects.isNull(id) || id.equals(0)) {
            log.error("FuelTypeServiceImpl.delete error id must not be null");
            throw new BaseException("主键不能为空");
        }

        FuelType fuelType = this.selectById(id);
        if(Objects.isNull(fuelType)){
            log.error("FuelTypeServiceImpl.delete error  must not be null");
            throw new BaseException("燃油信息不存在");
        }

        /**
         * 查询燃油类型是否跟燃油价格变动关联
         */
        EntityWrapper<FuelPriceEffective> ew = new EntityWrapper<>();
        ew.eq("fuel_type_id",id);
        List<FuelPriceEffective> fuelPriceEffectives = fuelPriceEffectiveService.selectList(ew);
        if (CollectionUtils.isNotEmpty(fuelPriceEffectives)) {
            log.error("DFuelTypeServiceImpl.delete error fuelPriceEffectives is not empty ");
            throw new BaseException("请先解除燃油类型和燃油价格变动的关联！");
        }

        return this.deleteById(id);
    }

    /**
     * 根据id得燃油类型
     *
     * @param id
     * @return
     */
    @Override
    public FuelTypeVO getById(Integer id) {
        FuelType fuelType = this.selectById(id);
        FuelTypeVO fuelTypeVO = new FuelTypeVO();
        BeanUtils.copyProperties(fuelType,fuelTypeVO);
        return  fuelTypeVO;
    }

    /**
     * 根据条件查询
     *
     * @param fuelTypeQueryConditionVO
     * @return
     */
    @Override
    public List<FuelTypeVO> selectListByConditions(FuelTypeQueryConditionVO fuelTypeQueryConditionVO) {
        log.info("FuelTypeServiceImpl.selectListByConditions params : {}", fuelTypeQueryConditionVO);

       EntityWrapper<FuelType> ew = new EntityWrapper<>();

        if (StringUtils.isNotBlank(fuelTypeQueryConditionVO.getFuelCode())) {
            ew.like("fuel_code", fuelTypeQueryConditionVO.getFuelCode());
        }
        if (StringUtils.isNotBlank(fuelTypeQueryConditionVO.getFuelName())) {
            ew.like("fuel_name", fuelTypeQueryConditionVO.getFuelName());
        }
        List<FuelType> fuelTypeList = this.selectList(ew);
        List<FuelTypeVO> listVO = Lists.newArrayList();
        fuelTypeList.forEach(fuelType -> {
            FuelTypeVO vo = new FuelTypeVO();
            BeanUtils.copyProperties(fuelType,vo);
            listVO.add(vo);
        });

        return  listVO;
    }

    /**
     * 查询条件
     * @return
     */
    private EntityWrapper<FuelType> whereCondition(Page<FuelTypeVO> page){
        EntityWrapper<FuelType> ew = new EntityWrapper<>();

        //条件
        if (Objects.nonNull(page.getCondition())){
            //燃油编码
            if (Objects.nonNull(page.getCondition().get("fuleCode")) && StringUtils.isNotEmpty(page.getCondition().get("fuleCode").toString())) {
                ew.eq("fuel_code", page.getCondition().get("fuleCode").toString().trim());
            }
            if (Objects.nonNull(page.getCondition().get("fuelName")) && StringUtils.isNotEmpty(page.getCondition().get("fuelName").toString())) {
                ew.eq("fuel_name", page.getCondition().get("fuelName").toString().trim());
            }
        }
        return ew;
    }

    /**
     * 验证是否符合条件
     * @param br
     */
    private void verificationForm(BindingResult br) {
        if (Objects.isNull(br)) {
            log.error("FuelTypeServiceImpl.verificationForm error br is null");
            throw new BaseException("BindingResult is null");
        }

        if (br.hasErrors()) {
            List<ObjectError> list = br.getAllErrors();
            log.error("FuelTypeServiceImpl.add error : {}", list.get(0).getDefaultMessage());
            throw new IllegalArgumentException(list.get(0).getDefaultMessage());
        }
    }


    /**
     * 判断是否重复
     * @param id
     * @param fuelName
     * @param fuelCode
     * @throws Exception
     */
    private void verificationCodeOrNameUnique(Integer id, String fuelName, String fuelCode){
        log.info("FuelTypeServiceImpl.verificationCodeOrNameUnique params : {}, {}", fuelCode, fuelName);

        if (StringUtils.isBlank(fuelCode)) {
            log.error("FuelTypeServiceImpl.verificationCodeOrNameUnique param fuelCode must not be null");
            throw new IllegalArgumentException("燃油类型编码不能为空");
        }
        if (StringUtils.isBlank(fuelName)) {
            log.error("FuelTypeServiceImpl.verificationCodeOrNameUnique param fuelName must not be null");
            throw new IllegalArgumentException("燃油类型名称不能为空");
        }

        EntityWrapper<FuelType> ew = new EntityWrapper<>();
        ew.eq("fuel_code",fuelCode);
        FuelType fuelType = this.selectOne(ew);

        if(Objects.nonNull(fuelType)){
            if (!fuelType.getId().equals(id)) {
                log.error("DFuelTypeServiceImpl.verificationCodeOrNameUnique error list is not empty");
                throw new BaseException("燃油编码已存在！");
            }
        }

        EntityWrapper<FuelType> ew1 = new EntityWrapper<>();
        ew1.eq("fuel_name",fuelName);
        fuelType = this.selectOne(ew1);
        if(Objects.nonNull(fuelType)){
            if (!fuelType.getId().equals(id)) {
                log.error("DFuelTypeServiceImpl.verificationCodeOrNameUnique error list is not empty");
                throw new BaseException("燃油名称已存在！");
            }
        }

    }
}
